package com.woniuxy.rbac.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.rbac.Global;
import com.woniuxy.rbac.entity.Perm;
import com.woniuxy.rbac.entity.ResponseResult;
import com.woniuxy.rbac.service.PermService;
import com.woniuxy.rbac.utils.Audience;
import com.woniuxy.rbac.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Auther: L
 */
@Slf4j
//@Order(2)
//@Component
//@WebFilter("/*")
public class AuthFilter implements Filter {
    @Autowired
    private Audience audience;

    @Autowired
    private PermService permService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //判断是否访问的是登录
        String url = req.getRequestURL().toString();
        String uri = req.getRequestURI();
        //log.debug("url:{},uri:{}", url, uri);
        if (uri.endsWith("/user/login")) {
            chain.doFilter(req, resp);
            return;
        }
        //不是访问的登录接口,判断是否已认证（判断是否带有合法有效的jwt）
        String jwt = req.getHeader("token");
        if (jwt == null) { //没有带jwt
            ResponseResult result = new ResponseResult<>(403, "no login");
            ObjectMapper objectMapper = new ObjectMapper();
            resp.getWriter().print(objectMapper.writeValueAsString(result));
            resp.getWriter().close();
        } else {
            //检验通过
            if (JwtUtil.verifyJwt(jwt, audience)) {
                //获取用户的所有权限
                int userId = JwtUtil.parseJwtForId(jwt, audience);
                List<Perm> perms = Global.perms;
                if (perms == null) {
                    perms = permService.getPermsByUserId(userId);
                    Global.perms = perms;
                }

                for (Perm perm : perms) {
                    if (perm.getLink().equals(uri)) {
                        chain.doFilter(req, resp);
                        return;
                    }
                }

////                Perm perm = permService.getByLink(uri);
//                if (perms.contains(perm)) {
//                    chain.doFilter(req, resp);
//                } else {
                ResponseResult result = new ResponseResult<>(403, "no login");
                ObjectMapper objectMapper = new ObjectMapper();
                resp.getWriter().print(objectMapper.writeValueAsString(result));
                resp.getWriter().close();
//                }
            } else {
                ResponseResult result = new ResponseResult<>(403, "no login");
                ObjectMapper objectMapper = new ObjectMapper();
                resp.getWriter().print(objectMapper.writeValueAsString(result));
                resp.getWriter().close();
            }
        }
    }
}
